package com.handtransaction.controller;

import com.handtransaction.entity.Goods;
import com.handtransaction.entity.Order;
import com.handtransaction.entity.User;
import com.handtransaction.service.GoodsService;
import com.handtransaction.service.OrderService;
import com.handtransaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author YAO
 * @create 2021-04-04 0:24
 */

/**
 * 处理订单功能的控制器
 */
@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    GoodsService goodsService;

    /**
     * 用户对订单的操作
     * 购买商品从而生成订单
     */
    @RequestMapping(value = "createOrder", method = RequestMethod.POST)
    public ModelAndView createOrder(ModelAndView modelAndView, Model model
            , HttpServletRequest request, HttpServletResponse response) {
//      获取买家信息
        User user = (User) request.getSession().getAttribute("user");
        Integer obid = user.getUid();
//        得到要购买的商品
        Goods goods = (Goods) request.getSession().getAttribute("good");

        orderService.createOrder(goods, obid);

        modelAndView.setViewName("common/succ");
        return modelAndView;
    }

    /**
     * 确认购买提交订单
     */
    @RequestMapping(value = "ensureOrder", method = RequestMethod.GET)
    public ModelAndView ensureMyOrder(
            ModelAndView modelAndView,
            @RequestParam(value = "gid", required = true) int gid,
            HttpServletRequest request, @RequestParam(value = "obid", required = true) int uid,
            Model model) {
        Goods goods = goodsService.QueryGoodBygid(gid);
        User user = userService.QueryUserByuid(uid);
        request.getSession().setAttribute("user", user);
        model.addAttribute("user", user);
        modelAndView.addObject("goods", goods);
        request.getSession().setAttribute("good", goods);
        //买家和卖家的id不可以相同
        Integer sellerId = goods.getGuid();
        if(sellerId == user.getUid()){
            model.addAttribute("idRepeat" ,500);
            modelAndView.setViewName("forward:ShowALLGoods");
            return modelAndView;
        }
        modelAndView.setViewName("order/ensureOrder");
        return modelAndView;
    }

    /**
     * 目前使用这个方法生成订单
     *
     * @param modelAndView
     * @param model
     * @param request
     * @param response
     * @param order
     * @return
     */

    @RequestMapping(value = "createOrder2", method = RequestMethod.POST)
    public ModelAndView createOrder2(ModelAndView modelAndView, Model model
            , HttpServletRequest request, HttpServletResponse response, Order order) {
//      获取买家信息
        User user = (User) request.getSession().getAttribute("user");
        Integer obid = user.getUid();
//        得到要购买的商品
        Goods goods = (Goods) request.getSession().getAttribute("good");
        int usid = goods.getGuid();
        User user2 = userService.QueryUserByuid(usid);

//        orderService.createOrder2(goods,obid);
        BigDecimal b1 = new BigDecimal(String.valueOf(user.getUbalance()));
        BigDecimal b3 = new BigDecimal(String.valueOf(user2.getUbalance()));
        BigDecimal b2 = new BigDecimal(String.valueOf(goods.getGprice()));
//        如果用户余额小于商品价格
        if (b1.compareTo(b2) == -1) {
            //System.out.println("用户" + user.getUname() + "的余额小于商品" + goods.getGname() + "的价格，无法购买");
            model.addAttribute("user", user);
            modelAndView.setViewName("common/error");
            return modelAndView;
//            如果用户余额大于等于商品价格
        } else if (b1.compareTo(b2) > -1) {
            orderService.createOrder2(order, obid);
            goodsService.updategtinyint(goods);
            BigDecimal res = b1.subtract(b2);
            BigDecimal res1 = b3.add(b2);
            user.setUbalance(res);
            user2.setUbalance(res1);
            userService.cutUbanlance(user);
            userService.addUbalance(user2);
        }
        modelAndView.setViewName("common/succ");
        return modelAndView;
    }

    /**
     * 获取所有订单
     *
     * @param modelAndView
     * @param request
     * @param response
     * @param obid         jsp页面传过来的当前用户id
     * @return
     */
    @RequestMapping(value = "checkMyOrder", method = RequestMethod.GET)
    public ModelAndView queryOrderByObid(ModelAndView modelAndView
            , HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "obid") Integer obid) {
        User user = (User) request.getSession().getAttribute("user");
        obid = user.getUid();
        // 获取所有订单信息
        List<Order> orderlist = orderService.searchOrdersByobid(obid);
        List<Order> orderlist1 = orderService.searchOrdersByosid(obid);
        modelAndView.addObject("orderslist", orderlist);
        modelAndView.addObject("orderslist1", orderlist1);
        modelAndView.setViewName("order/ordermanage");
        return modelAndView;
    }

    /**
     * 处理用户删除自己的订单
     *
     * @param modelAndView
     * @param oid
     * @return
     */
    @RequestMapping(value = "deleteOrder", method = RequestMethod.GET)
    public ModelAndView deleteOrder(ModelAndView modelAndView,
                                    @RequestParam(value = "oid") Integer oid) {
//      根据订单号删除订单
        orderService.deleteorder(oid);
        modelAndView.setViewName("common/succ");
        return modelAndView;
    }


    /**
     * 管理员对订单的操作
     */
    @RequestMapping("/showAllOrder")
    public String showAllOrder(Model model) {
        List<Order> orderList = orderService.queryAllOrder();
        model.addAttribute("orderList", orderList);
        return "order/showAllAdminOrders";
    }

    @RequestMapping("/queryOrderByAdmin")
    public String queryOrderByAdmin(Integer id, String queryType, Model model) {
        if (queryType.equals("orderId")) {
            Order order = orderService.queryOrderByAdminByOid(id);
            List<Order> orderList = new ArrayList<>();
            orderList.add(order);
            model.addAttribute("orderList", orderList);
            return "order/showAllAdminOrders";
        }
        if (queryType.equals("userId")) {
            List<Order> orderList = orderService.queryOrderByAdminByUserId(id);
            model.addAttribute("orderList", orderList);
            return "order/showAllAdminOrders";
        }
        if (queryType.equals("buyerId")) {
            List<Order> orderList = orderService.queryOrderByAdminByObid(id);
            model.addAttribute("orderList", orderList);
            return "order/showAllAdminOrders";
        }
        if (queryType.equals("sellerId")) {
            List<Order> orderList = orderService.queryOrderByAdminByOsid(id);
            model.addAttribute("orderList", orderList);
            return "order/showAllAdminOrders";
        }
        return "order/showAllAdminOrders";
    }

    @RequestMapping("/deleteOrderByAdmin")
    public String deleteOrderByAdmin(Integer oid) {
        orderService.deleteOrderByAdmin(oid);
        return "redirect:/showAllOrder";
    }


}
